subroutine WriteRes()
use Data_cfoam, only: processor,ie,rank, outRestarts, nResOut, &
                      Unew,pnew,Tnew, Usnew,psnew,Rhosnew, utmp, ierr
use DataTime, only: ttime,dt,nstep
use Data_Mesh, only: nCells,nFaces
implicit none
    include 'mpif.h'

    character(7) :: String7Number
    integer :: i, OpenFile

    call Number2String(String7Number,nResOut)

    open(32,file=processor(1:ie)//'ResCells'//String7Number(1:7),form='unformatted',IOSTAT=OpenFile)
    if (OpenFile.ne.0) then
	    write(*,*) '@@ Fatal Error (WriteRes): File open error '//processor(1:ie)//'ResCells'//String7Number(1:7)
	    STOP '@@ Fatal Error!'
    end if

 	open(outRestarts,file=processor(1:ie)//'ResFaces'//String7Number(1:7),form='unformatted',IOSTAT=OpenFile)
    if (OpenFile.ne.0) then
	    write(*,*) '@@ Fatal Error (WriteRes): File open error '//processor(1:ie)//'ResFaces'//String7Number(1:7)
	    STOP '@@ Fatal Error!'
    end if

    write(32) ttime,0,nCells !,(U(1:3,i),p(i),T(i),i=1,nCells) !,E(i),rho(i)
    write(32) (Unew(1:3,i),pnew(i),Tnew(i),i=1,nCells) !,Enew(i),rhonew(i)
    write(outRestarts) ttime,nstep+1,dt,0,nFaces !,(Usnew(1:3,i),psnew(i),Rhosnew(i),i=1,nFaces) !,Esnew(i),Tsnew(i)
    write(outRestarts) (Usnew(1:3,i),psnew(i),Rhosnew(i),i=1,nFaces) !,Esnew(i),Tsnew(i)
    write(outRestarts) 0,100 !,(utmp(1:8,i),i=1,100)
    write(outRestarts) (utmp(1:8,i),i=1,100)

    close(32)
    close(outRestarts)

    call MPI_Barrier(MPI_COMM_WORLD,ierr)

    if(rank.eq.0)then
        write(*,*) 'Restarts No', nResOut-1, ' have been written successfully'
    end if

end subroutine WriteRes

subroutine Number2String(String7Number,n)
implicit none

    character(*),intent(out) :: String7Number
    integer,intent(inout) :: n
    integer :: j

    write(String7Number(1:7),'(i7)') n
    do j= 1, 7 !4,10
        if(String7Number(j:j).eq.' ') String7Number(j:j) = '0'
    end do
    
    n = n + 1

end subroutine Number2String